﻿using System;
using System.IO;
using System.Management;
using System.Net;
using System.Xml.Serialization;

namespace QunFaExpert
{
    public class OnlineLicense
    {
        static WebClient wc = new WebClient();
        private readonly string storefile = "guidvalue.xml";
        private string cpu;
        public string Cpu
        {
            get
            {
                if (string.IsNullOrEmpty(cpu))
                {
                    try
                    {
                        GuidStore result;
                        var ser = new XmlSerializer(typeof (GuidStore));
                        using (var fs = new FileStream(storefile, FileMode.Open, FileAccess.Read))
                        {
                            result = ser.Deserialize(fs) as GuidStore;
                            if (result != null) return cpu = result.g;
                        }
                        cpu = CreateNewGuidAndStore();
                    }
                    catch
                    {
                        cpu = CreateNewGuidAndStore();
                    }

                }
                return cpu;
            }
        }

        private string CreateNewGuidAndStore()
        {
            var guidStore = new GuidStore { g = Guid.NewGuid().ToString("N") };
            var ser = new XmlSerializer(typeof(GuidStore));
            using (var fs = new FileStream(storefile, FileMode.Create, FileAccess.Write))
            {
                ser.Serialize(fs, guidStore);
            }
            return guidStore.g;
        }
        private string SofaUrl = "http://y182319.51host.net/sf.php?ID={0}";
        public int GetLeftSofaAmount()
        {
            var result = wc.DownloadString(string.Format(SofaUrl, Cpu));
            return int.Parse(result);
        }
    }
    public class GuidStore
    {
        public string g;
        public GuidStore() { }
    }

}
